package com.farsunset.cim.sdk.server.slc.coder;

import com.farsunset.cim.constant.ChannelAttr;
import com.farsunset.cim.model.Pong;
import com.farsunset.cim.model.SentBody;
import com.farsunset.cim.sdk.server.slc.constant.SlcCIMConstant;
import com.farsunset.cim.sdk.server.slc.constant.SlcChannelAttr;
import com.farsunset.cim.sdk.server.slc.utils.ChannelWriteTransform;
import com.farsunset.cim.sdk.server.slc.utils.CimGsonUtils;
import com.farsunset.cim.sdk.server.slc.utils.CimStringUtils;
import com.google.gson.JsonSyntaxException;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;

/**
 * @author slc
 * @date 30/8/2021 下午 3:02
 */
public class TextMessageDecoderDelegate {
    /**
     * 解码
     *
     * @param ctx
     * @param text
     * @param out
     */
    public void decoder(ChannelHandlerContext ctx, String text, List<Object> out) {
        if (decoderPong(ctx, text, out)) {
            return;
        }
        decoderText(ctx, text, out);
    }

    /**
     * 解码字符串
     *
     * @param ctx
     * @param text
     * @param out
     */
    public void decoderText(ChannelHandlerContext ctx, String text, List<Object> out) {
        SentBody body;
        try {
            body = CimGsonUtils.fromJson(text, SentBody.class);
        } catch (JsonSyntaxException e) {
            body = new SentBody();
            body.getData().put("content", text);
            body.getData().put("sender", ctx.channel().id().asShortText());
        }
        String writeType = body.get(SlcChannelAttr.WRITE_TYPE.name());
        if (writeType == null || writeType.length() == 0) {
            //如果没有给出明确的写入类型 则直接设定为json
            body.getData().put(SlcChannelAttr.WRITE_TYPE.name(), ChannelWriteTransform.KEY_JSON);
        }
        if (body.getKey() == null || body.getKey().length() == 0) {
            body.setKey(SlcCIMConstant.HANDLER_LOSE_WAY);
        }
        out.add(body);
    }

    /**
     * 解码心跳
     *
     * @param ctx
     * @param text
     * @param out
     * @return
     */
    public boolean decoderPong(ChannelHandlerContext ctx, String text, List<Object> out) {
        if (SlcCIMConstant.VALUE_PONG.equals(text)) {
            out.add(Pong.getInstance());
            return true;
        }
        return false;
    }

    /**
     * 粗略的估计是否注册
     *
     * @param ctx
     * @return
     */
    protected boolean sketchyIsBinding(ChannelHandlerContext ctx) {
        String id = ctx.channel().attr(ChannelAttr.ID).get();
        String uid = ctx.channel().attr(ChannelAttr.UID).get();
        return !CimStringUtils.isEmpty(id) && !CimStringUtils.isEmpty(uid);
    }
}
